package com.apes.crm.business.repository;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.query.ApesDao;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @program:
 * @description:
 * @author: lws
 * @create: 2023/1/30 14:38
 **/
@Component
public class InsuranceCompanyDao extends ApesDao {

    public List findAllByCarAccident(JSONObject param) {
        String sSQL = " select a.id\n" +
                "       from crm_insurance_company a\n" +
                "       where a.company_id in ('1001', '1007') ";
        if (param.containsKey("query") && param.getString("query").equals("group") && param.containsKey("value")){
            // 文本框查询
            String value = param.getString("value");
            if (!Objects.isNull(value) && value.length() > 0){
                String str = formatterName(value);
                sSQL += " and (a.id like '%" + value + "%'\n";
                sSQL += " or a.name like '%" + str + "')\n";
            }
        }else if (param.containsKey("query") && param.getString("query").equals("condition")){
            // 弹框查询
            if (param.containsKey("id")) sSQL += " and a.id = '" + param.getString("id") + "'\n";
            if (param.containsKey("name")){
                String str = formatterName(param.getString("name"));
                sSQL += " and a.name like '%" + str + "'\n";
            }
        }
        JSONArray jsonArray = toJSONArray(find(sSQL, param));
        return jsonArray.stream().map(item -> {
            return ((JSONObject) item).getString("ID");
        }).collect(Collectors.toList());
    }

    private String formatterName(String value){
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < value.length(); i++) {
            char c = value.charAt(i);
            sb.append(c + "%");
        }
        return sb.toString();
    }
}
